package algebra.visitors.cursors;

import utils.exception.CoreReasoningException;
import algebra.op.AlgebraicOP;
import algebra.op.SelectionOP;
import algebra.visitors.AlgebraicOPEvaluator;
import entities.assertion.ConceptAssertion;

public class CACursorSelection extends CACursor {
	private CACursor subcursor;
	private final SelectionOP op;
	private ConceptAssertion subres;
//	PrintStream s;

	public CACursorSelection(SelectionOP op) {
		this.op = op;
		this.subcursor = null;
	}

	@Override
	public boolean openCursor() {
		// create a new cursor for subresults
		AlgebraicOP subop = this.op.getSubquery();
		this.subcursor = CACursor.getNewCACursor(subop);
		this.subcursor.openCursor();
//		try {
//			FileOutputStream fw = new FileOutputStream("log.txt");
//			s = new PrintStream(fw);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		return true;
	}
	
	@Override
	public ConceptAssertion getNextResult() {
		subres = this.subcursor.getNextResult();
		if(subres == null){
			return null;
		}
		ConceptAssertion ret = null;
		while(subres != null){
			try {
				ret = new AlgebraicOPEvaluator().EvaluateSelectionQueryPipelined(op, subres);
			} catch (CoreReasoningException e) {
				e.printStackTrace();
			}
			if(ret != null){
				return ret;
			}
			subres = this.subcursor.getNextResult();
		}
		return null;
	}

	@Override
	public boolean isSortedById() {
		return this.subcursor.isSortedById();
	}


}
